package com.kedacom.demo.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * HashSerializer
 * @author luocanfeng
 * @date 2015年9月8日
 */
public class HashSerializer {

	/**
	 * 将对象转换成Map
	 */
	public static Map<String, String> toMap(Object obj) {
		Map<String, String> map = new LinkedHashMap<String, String>();
		List<String> fieldNames = getFieldNames(obj.getClass());
		// Collections.sort(fieldNames);
		for (String fieldName : fieldNames) {
			try {
				String value = BeanUtils.getSimpleProperty(obj, fieldName);
				if (StringUtils.isNotEmpty(value)) {
					map.put(fieldName, value);
				}
			} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
				e.printStackTrace();
			}
		}
		return map;
	}

	/**
	 * 获取属性名列表
	 */
	public static List<String> getFieldNames(Class<?> clazz) {
		List<String> fieldNames = new ArrayList<String>();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			fieldNames.add(field.getName());
		}
		return fieldNames;
	}

}
